// const Category = require('../../models/Category')

module.exports = app => {
    const express = require('express')
       
    const AdminUser = require('../../models/AdminUser')
    // jwtwebtoken  
    const jwt = require('jsonwebtoken')

    const assert = require('http-assert')
    // express 的子路有
    // 合并url参数mergeParams:true
    const router = express.Router({
        mergeParams: true
    })

    // const Caregroy= require('../../models/Category')

    //在每一个路由里面找出他的路由是什么

    // 通用CRUD

    //  提交数据
    router.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    })

    // 登录校验中间件
      const authMiddleware = require('../../middleware/auth')
      const resourceMiddleware = require('../../middleware/resource')
      app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(), router)
    // 展示数据
    // 原本Caregroy模型里parent字段只能查询id 通过populate 关联取出整个对象信息
    router.get('/', async (req, res) => {
        // 如果模型有分类的话 判断
        const queryOptions = {}
        if (req.Model.modelName === 'Category') {
            queryOptions.populate = 'parent'
        }
        const items = await req.Model.find().setOptions(queryOptions).limit(100)
        res.send(items)
    })

    // 回显
    router.get('/:id', async (req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })

    // 修
    router.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })

    // 删除
    router.delete('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndDelete(req.params.id)
        res.send({
            success: true
        })
    })

    app.use('/admin/api/rest/:resource', async (req, res, next) => {
        // npm i  inflection  处理单复数的转换  转类名 转大写
        const modelName = require('inflection').classify(req.params.resource)

        // const Model = require(`../../models/${req.params.resource}`) 
        //找模型 转大写
        req.Model = require(`../../models/${modelName}`)
        next()
    }, router)






    // 图片处理
    //因为express是直接获取不到图片的 需要一个中间件处理
    const multer = require('multer')
    // const upload = multer({ dest: __dirname + '/../../uploads' })
        const MAO = require('multer-aliyun-oss');
    const upload = multer({
      // dest: __dirname + '/../../uploads',
      storage: MAO({
        config: {
          region: 'oss-cn-hongkong',
          accessKeyId: 'LTAI4GL8d8wMMkyjSVkfuT92',
          accessKeySecret: 'Votxy4JcX95b79stSeE29yVvTZXcV9',
          bucket: 'node-vue-fcc'
        }
      })
    })
    // single('')单文件的上传
    app.post('/admin/api/upload',authMiddleware(), upload.single('file'), async (req, res) => {
        const file = req.file
        // file.url = `http://test.fcc-zhiciliuniangetianya.com:3000/uploads/${file.filename}`
        res.send(file)
    })


    // 用户登录的路由
    app.post('/admin/api/login', async (req, res) => {
        const { username, password } = req.body

        // 1.把模型提出来 根据用户名找用户  select('+password') 表示把password字段取出来 

        const user = await AdminUser.findOne({ username }).select('+password')
        assert(user, 422, '用户不存在')

        // 2.校验密码   用bcrypt中间件校验 compareSync 比较铭文和密文是否匹配
        const isValid = require('bcrypt').compareSync(password, user.password)
        assert(isValid, 422, '密码错误')

        // 3.返回token    secret表示的是生成用户token的时候给一个秘钥
        const token = jwt.sign({ id: user._id }, app.get('secret'))
        res.send({ token })

        // 错误处理函数
        app.use(async (err, req, res, next) => {
            // console.log(err)
            res.status(err.statusCode || 500).send({
                message: err.message
            })
        })
    })


}